package org.vacoor.ticket.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class StationInfoDownloader {
	private static final String cityQueryUrl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=getStationName&from_station_name=";
	private static int count ;

	public static void getCityInfoFromsHttps2File(String path) {
		count = 0;
		PrintWriter out;
		try {
			out = new PrintWriter(path);
			out.println("# 信息格式为:编号-城市名称-城市拼音代码-车站代码,每条信息之间以:分隔");
			for (char i = 'A'; i <= 'Z'; i++) {
				for (char j = 'A'; j <= 'Z'; j++) {
					for (char k = 'A'; k <= 'Z'; k++) {
						BufferedReader bi = new BufferedReader(
								new InputStreamReader(NetworkDownloadUtil
										.getInputStreamFromHttps(cityQueryUrl
												+ i + j + k)));
						String citys;
						while ((citys = bi.readLine()) != null) {
							System.out.println("读到数据:" + citys);
							for(String s : ParseUtil.parseStatioinInfo(citys)) {
								out.print((++count) + "-" + s + ":");
								System.out.println("写入数据:" + s);
							}
							out.flush();
						}
						bi.close();
					}
				}
			}
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void getInfoFromFile2File(String src,String dst) {
		count = 0;
		BufferedReader br = null;
		PrintWriter pw = null;
		try {
			br = new BufferedReader(new FileReader(src));
			pw = new PrintWriter(dst);
			pw.println("# 信息格式为:编号-城市名称-城市拼音代码-车站代码,每条信息之间以:分隔");
			String line;
			while((line = br.readLine()) !=null) {
				System.out.println("读到数据:" + line);
				for(String s : ParseUtil.parseStatioinInfo(line)) {
					pw.print((++count) + "-" + s + ":");
					System.out.println("写入数据:" + (++count) + "-" + s + ":");
				}
				pw.flush();
			}
			br.close();
			pw.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
//		getCityInfoFromsHttps2File("citysInfo.txt");
		getInfoFromFile2File("12306.city.json", "citysInfo.txt");
	}
}
